package network

import (
	"net"
)

const READ_MAX_BUFFER = 1024

func ReadMessage(conn net.Conn, callback func(net.Conn, *Message)) error {

	tmpBuffer := make([]byte, 0)
	buffer 	  := make([]byte, READ_MAX_BUFFER)
	readChan  := make(chan *Message)

	go func() {
		for {
			select {
			case message := <-readChan:
				callback(conn, message)
			}
		}
	}()

	for {
		b, err := conn.Read(buffer)
		if err != nil {
			return err
		}

		tmpBuffer = Unpack(append(tmpBuffer, buffer[:b]...), readChan)
	}
}

func SendMessage(conn net.Conn, code int, data []byte) (err error) {

	if _, err := conn.Write(Packet(code, data)); err != nil {
		return err
	}

	return nil
}